package com.zjitc.pigstudy.common;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.zjitc.pigstudy.Exception.ServiceException;
import com.zjitc.pigstudy.domain.User;
import com.zjitc.pigstudy.mapper.UserMapper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("我拦截了");


        String token = "";  //header里面传过来的参数
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK );
            return true;
        }else{
            token = request.getHeader("token");
        }

        if(token==null||"".equals(token)){
            token = request.getParameter("token");  //url参数 ？token=xxxx
        }
        //如果不是映射到方法直接通过
        if(handler instanceof HandlerMethod){
            AuthAccess annotation = ((HandlerMethod)handler).getMethodAnnotation(AuthAccess.class);
            if(annotation != null){
                return true;
            }
        }
        //执行认证
            if (token == null || "".equals(token)) {
                throw new ServiceException("401", "请登录1");
            }
            //获取token中的user id
            String userId;
            try {
                userId = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException j) {
                throw new ServiceException("401", "请登录2");
            }

            //根据token中的userId查询数据库
            User user = userMapper.selectById(Integer.parseInt(userId));
            if (user == null) {
                throw new ServiceException("401", "请登录3");
            }
            //通过用户密码加密之后生成一个验证器
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTDecodeException e) {
                throw new ServiceException("401", "请登录4");
            }

        return true;
    }
}
